using System;
using System.Threading;
using Microsoft.SPOT;

namespace NetduinoHappyHour.Asynchronous
{
    /// <summary>
    /// Abstract class to provide base handling for threaded environment
    /// </summary>
    public abstract class BaseAsyncHandler : IExecutable
    {
        private readonly object _lock = new object();
        private bool _isStarted = false;
        private Thread _processor;

        public bool IsStarted { get { return _isStarted; } }

        /// <summary>
        /// The thread procedure to be implemented. This method will be called when thread is started.
        /// </summary>
        public abstract void ThreadProc();

        public bool Start()
        {
            lock (_lock)
            {
                if (_isStarted)
                {
                    return false;
                }
                _isStarted = true;
                _processor = new Thread(ThreadProc);
                _processor.Start();
            }
            return true;
        }

        public bool Stop()
        {
            lock (_lock)
            {
                if (!_isStarted)
                {
                    return false;
                }
                _isStarted = false;
                if (!_processor.Join(5000))
                {
                    _processor.Abort();
                }
                return true;
            }
        }

        public void Execute()
        {
            Start();
        }

    }
}
